import React, { useContext, useState } from "react";
import {
  View,
  Text,
  StyleSheet,
  FlatList,
  TouchableOpacity,
  Alert,
} from "react-native";
import SampleVillageCard from "../../components/preAdmin/SampleVillageCard";
import SampleVillageContext from "../../context/preparation/SampleVillageContext";
import { AntDesign } from "@expo/vector-icons";
import NoData from "../../components/preAdmin/NoData";
import LoadingBar from "../../components/InterView/LoadingBar";

const SampleVillageManage = ({ navigation }) => {
  const { villageLists, deleteSampleVillage, isVillageLoading } =
    useContext(SampleVillageContext);
  const [isDelete, setIsDelete] = useState(false);
  const [deletedId, setDeletedId] = useState(null);

  React.useLayoutEffect(() => {
    navigation.setOptions({
      headerRight: () => (
        <TouchableOpacity
          onPress={() => {
            setIsDelete((pre) => setIsDelete(!pre));
          }}
        >
          <AntDesign name="delete" size={22} color="#fff" />
        </TouchableOpacity>
      ),
    });
  }, [navigation]);

  const onConfirmeDeleted = (id) => {
    setDeletedId(id);
    Alert.alert("提示", "你确定要删除该样本村吗?", [
      {
        text: "确定",
        onPress: () => {
          deleteSampleVillage(id);
        },
      },
      {
        text: "取消",
      },
    ]);
  };

  return (
    <View style={styles.container}>
      <LoadingBar visible={isVillageLoading} />
      <FlatList
        data={villageLists}
        ListEmptyComponent={<NoData />}
        keyExtractor={(item, index) => {
          return index.toString();
        }}
        renderItem={({ item, index }) => (
          <SampleVillageCard
            item={item}
            index={index}
            isDelete={isDelete}
            onDeleted={onConfirmeDeleted}
            deletedId={deletedId}
            isVisible={true}
            onPress={() =>
              navigation.navigate("SampleVillageEdit", {
                sampleVillage: item,
              })
            }
          />
        )}
      />
      <TouchableOpacity
        style={styles.Button}
        onPress={() => navigation.navigate("SampleVillageAdd")}
      >
        <Text style={styles.Text}>创建样本村</Text>
      </TouchableOpacity>
    </View>
  );
};

var styles = StyleSheet.create({
  container: {
    height: "100%",
    backgroundColor: "#f5f5f5",
    padding: 10,
  },
  Button: {
    borderRadius: 5,
    margin: 10,
    padding: 10,
    backgroundColor: "#3ABEF0",
    alignItems: "center",
    justifyContent: "center",
    elevation: 2, //设置阴影角度，通过这个设置有无阴影
    shadowColor: "gray", // 设置阴影色
  },
  Text: {
    fontSize: 16,
    color: "#fff",
    fontWeight: "bold",
  },
});

export default SampleVillageManage;
